var poiExcelUtils = (function($) {
	return {
		importExcel:function($table,url){
			var layerIndex;
			var callback = 'uploadCallback';
			
			var prefix = 'importExcel';
			
			if($('body').find('#'+prefix+'Frame').length<1){
				$('body').append('<iframe id="'+prefix+'Frame" name="'+prefix+'Frame" style="display:none;"></iframe>');
			}
			if($('body').find('#'+prefix+'Form').length<1){
				$('body').append('<form id="'+prefix+'Form" style="display:none;" action="'+url+'" method="post" enctype="multipart/form-data" target="'+prefix+'Frame"><input type="hidden" name="callback" value="'+callback+'"/><input class="'+prefix+'Input" type="file" name="file" style="display: none;"/></form>');
			}
			
			$('body').find('#'+prefix+'Form').attr('action',url);
			
			$('body').find('#'+prefix+'Form').find('.'+prefix+'Input').change(function(){
				layerIndex = pageUtils.loadBar();
				var filePath = $(this).val();
				
				if(!filePath){
					return;
				}
				
				var includeExts = ['xls','xlsx'];
				
				var suffix = filePath.substring(filePath.lastIndexOf('.')+1);
	        	 
	        	if($.inArray(suffix.toLowerCase(),includeExts)==-1){
	        		PgfaUtils.error('只能上传'+includeExts+'格式的文件！');
	        		layer.close(layerIndex);
	        		return;
	        	}
				var file = this.files[0];
				
				$('body').find('#'+prefix+'Form').submit();
				
			});
			
			window[callback] = function(json){
				layer.close(layerIndex);
				$('body').find('#'+prefix+'Form').find('.'+prefix+'Input')[0].value='';
				
				if(json.count>0){
					PgfaUtils.success(json.resultMsg);
					$table.trigger("reloadGrid");
				}else{
					PgfaUtils.error(json.resultCode||json.resultMsg);
				}
			}
			
			$('body').find('#'+prefix+'Form').find('.'+prefix+'Input').click();
		},
		exportExcel:function($table,url){
			var postData = $table.getGridParam('postData');
			
			var colNames = new Array();
			var colModels = $table.getGridParam('colModel');
			for(var i = 1; i < colModels.length; i ++){
				if(!colModels[i].hidden){
					colNames.push(colModels[i].name);
				}
			}

			var jsonRequest = {extend:{colNames:colNames},orderBy:postData['sidx'],orderDirection:postData['sord'],pageNo:postData['page'],pageSize:postData['rows'],condition:postData['condition']};
			
			location.href = url +(url.indexOf('?')!=-1?'&':'?')+"jsonRequest="+encodeURIComponent(JSON.stringify(jsonRequest));
		},
		/**
		 * 通用导入方法
		 * @param required 是必填字段数组
		 * @param unrequired 是不填字段数组
		 * @param parseExcelUrl 是读取Excel表的请求
		 * @param verifyExcelUrl 是校验Excel表的请求
		 * @param insertExcelUrl 导入数据到数据库的请求
		 * @param $tableName 是子表的table或者单表的Form，例如 var table = "form";
		 * @param judgeType 是判断是单表还是多表，0代表单表，1代表多表
		 * @param box 如果有radio或者checkbox，需要把中文转换成对应的值。ps：{"启用状态"：{"未启用"："N","启用":"Y"},"储位类型":{"固定储位":"1","移动储位":"2","待检储位":"3"}}
		 * @param extend 读取Excel表请求带的参数（字符串）
		 * @param extend1 校验Excel表请求带的参数（form-extend的格式）
		 * @param extend2 导入数据请求带的参数（form-extend的格式）
		 * @param beforeFunc 导入jqGrid表格前执行的用户自定义函数
		 * @param beforeParam beforeFunc的参数
		 * @param afterFunc 导入jqGrid表格后执行的用户自定义函数
		 * @param afterParam afterFunc的参数
		 * @param bomStartSeq BOM导入开始行 字符串
		 */
		importByExcel:function(required,unrequired,parseExcelUrl,verifyExcelUrl,insertExcelUrl,tableName,judgeType,box,extend,extend1,extend2,
				beforeFunc,beforeParam,afterFunc,afterParam,bomStartSeq){
			
			var requiredArr = required;
			var unrequiredArr = unrequired;
			var sheetDataList = [];//Excel表数据（每个sheet对应一个数据数组）
			var tableFieldsMap = [];//保存了整个表的字段名
			var messageMap = {};
			var sheetNames = [];//保存Excel表中每个sheet的名字
			var sheetListMap = [];
			var selectParams = [];
			var sheetData = [];//保存一个sheet的内容
			var colName = [];//保存表头
			var colModel = [];//保存每行字段的属性
			var nameMapValue = box;//将中文映射成值
			var $tableName = $("#"+tableName)
			var gview_table = $("#gview_"+tableName+" .ui-jqgrid-htable thead th");//jqGrid列标题
			var jqGridHeader = {};//保存jqGrid列表的列标题键值对，key为字段中文名称，value为字段英文代码
			var jqGridEnToCn = {};//保存jqGrid列表的列标题键值对，key为字段英文名称，value为字段中文代码
			var fileFormData = null; // 保存Excel文件数据
			var isBom = "N";
			if(bomStartSeq){
				isBom = 'Y';
			}
			
			//根据jqGrid获取表头的字段名称和代码
			for(var i = 1; i < gview_table.length; i++){
				jqGridHeader[($(gview_table[i]).find("div").text()).replace(/[\r\n\t]/g,"")] = $(gview_table[i]).find("div").attr("id").split("_")[($(gview_table).find("div").attr("id").split("_")).length - 1];
				jqGridEnToCn[$(gview_table[i]).find("div").attr("id").split("_")[($(gview_table).find("div").attr("id").split("_")).length - 1]] = ($(gview_table[i]).find("div").text()).replace(/[\r\n\t]/g,"");
			}
			console.log(jqGridHeader);
			
			//开始
			step_1();
			//封装生成表格和卡片方法
		    function selfTabel(elId, options) {
		        var parentBox = $(elId);
		        //清空包容块
		        parentBox.html("");

		        //创建表格包容元素
		        var tabelElBox = $("<div class='table_phone'></div>");
		        var tabe1Id =  parentBox.attr("id")+"Table";
		        var tabelEl = $("<table id='" + tabe1Id + "'></table>");
		        tabelElBox.append(tabelEl);
		        parentBox.append(tabelElBox);

		        //创建卡片包裹元素
		        if (options.card) {
		            var cadBox = $("<div class='phone_table'></div>");
		            var cadUl = $("<ul></ul>");
		            cadBox.append(cadUl);
		            parentBox.append(cadBox);
		        }
		        var defaults = {
		            autowidth: true,
		            rowNum: 10,//一页显示多少条
		            sortorder: "desc",//排序方式,可选desc,asc
		            altRows: true,
		            altclass: 'diff_rows',
		            shrinkToFit: true,
		            autoScroll: true,
		            mtype: "post",//向后台请求数据的ajax的类型。可选post,get
		            viewrecords: true,
		            forceFit: true,
		            datatype: "json",
		            multiselect: true,
		            multiselectWidth: 30,
		            height: 'auto',
		            sortname: 'updatedDate',
		        };
		        var opts = $.extend({}, defaults, options);
		        opts.loadComplete = function (data) {
		            if (options.loadComplete) options.loadComplete(data);
		            if (opts.card) {
		                cadUl.html("");
		                var d = data.rows;
		                if(!d) return;
		                for (var i = 0; i < d.length; i++) {
		                    var l = d[i];
		                    var html = $("<li data-id='" + l.id + "' style='min-height: 130px'></li>");
		                    //添加标题
		                    var title = $("<p class='title'>" + l.id + "</p>");
		                    if (!options.multiselect) {
		                        html.append(title);
		                    } else {
		                        var checkBox = $("<label><div class=\"checkbox-label\"><input type=\"checkbox\" name='" + l.id + "'><span></span></div></label>")
		                        checkBox.append(title);
		                        html.append(checkBox);
		                    }
		                    if (options.card.menu) {
		                        //添加弹出块
		                        var upBoxLabel = $("<label class='close-upbox'><input type='checkbox'><span class='title-icon'><span></span></span></label>");
		                        var upBox = $("<div class='upBox'></div>");
		                        upBoxLabel.append(upBox);
		                        html.append(upBoxLabel);
		                        for (var z = 0; z < options.card.menu.length; z++) {
		                            var dom = $("<span data-seletName='" + options.card.menu[z].name + "' event='upbox_operation'><span><i class='" + options.card.menu[z].icon + "'></i><br/>" + options.card.menu[z].text + "</span></span></span>")
		                            upBox.append(dom);
		                        }
		                    }
		                    //添加内容
		                    var paremtbox = $("<div class='centent' event='card-click'></div>");
		                    var leftBox = $("<div class='cent-left'></div>");
		                    var rightBox = $("<div class='cent-right'></div>");
		                    paremtbox.append(leftBox).append(rightBox);
		                    html.append(paremtbox);
		                    for (var k = 0; k < l.cell.length; k++) {
		                        if (k < 4) {
		                            var text;
		                            if (typeof l.cell[k] == 'string') {
		                                if (k < 1) {
		                                    text = $("<h2>" + l.cell[k] + "</h2>")
		                                } else {
		                                    text = $("<p>" + l.cell[k] + "</p>")
		                                }
		                                leftBox.append(text);
		                            }
		                        }
		                        if (l.cell[k].type && l.cell[k].type === "label" && l.cell[k].cell.length) {
		                            var labs = l.cell[k].cell;
		                            for (var ls = 0; ls < labs.length; ls++) {
		                                var classNmae = labs[ls].type;
		                                var text = labs[ls].text;
		                                var span = $("<span class='state " + classNmae + "'>" + text + "</span>")
		                                rightBox.append(span);
		                            }
		                        }
		                    }
		                    cadUl.append(html);
		                }
		            }
		        };
		        jqgridInit("#" + tabe1Id, opts);
		        $(window).resize(function () {
		            //jqgrid自适应
		            $("#" + tabe1Id).setGridWidth($(".ts_table>.table_phone").width());
		        });
		    }
			
		    //对于后加载的表格,新增tooltip
		    $("#stuff_list").tooltip({
		        selector: '[data-toggle="tooltip"]'
		    });
		    $("#stuff_list2").tooltip({
		        selector: '[data-toggle="tooltip"]'
		    });
		    
			//上传Excel弹窗step_1()
			function step_1(){
		        //步骤弹窗
		        var step1 = $("#step1").html();
		        //统一弹窗设置

		        //获取窗口高度
		        var index1 = layer.open({
		            type: 1,
		            title:'导入',
		            skin:"layer_upBox stepBoz1",
		            area:['980px','160px'],
		            resize: false,
		            shadeClose: true, //点击遮罩关闭
		            content: step1,
		            btnAlign: 'c',
		            zIndex:100,
		            success:function(){
		                //由于插件在内容过多的情况下计算高度会有问题(这里做修复)
		                var upBox = $(".stepBoz1");
		                var height = Number(upBox.height()) - 42;
		                upBox.find(".layui-layer-content").css("height",height+"px");
		                //点击放弃
		                $("#closeindex1").on("click",function(){
		                    layer.close(index1)
		                });
		                //加载文件
		                publicUtils.loadFileinput("#input-iconic1",{preferIconicPreview:false,showPreview:false});
		                 
		                $('#input-iconic1').on('fileselect', function(event, numFiles, label) {
		            		var formData = new FormData();
		            		fileFormData = $('#input-iconic1')[0].files[0];
		            		formData.append('file',$('#input-iconic1')[0].files[0]);
		            		formData.append('reParam',required);
		            		if(extend){
		            			formData.append('extend',extend);
		            		}else{
		            			formData.append('extend',"");
		            		}
		            		if(bomStartSeq){
		            			formData.append('bomStartSeq',bomStartSeq);
		            		}else{
		            			formData.append('bomStartSeq',"");
		            		}
		            		$.ajax({url : parseExcelUrl,type : "POST",cache : false,
		            			data : formData,
		            			traditional : true,//设置为true,否则后台接收的参数会带上[]，无法正常接收
		            			processData : false,
		            			contentType : false,
		            			dataType : "json",
		            			success : function(data) {
		            				if (data.resultCode == '0000') {
		            					sheetDataList = [];
		            					tableFieldsMap = [];
		            					messageMap = [];//保存必填字段
		            					sheetDataList = data.extend.sheetListMap;//Excel表数据（每个sheet对应一个数据数组）
		            					tableFieldsMap = data.extend.tableFieldsMap;//保存了整个表的字段名
		            					sheetNames=[];
		            					selectParams=[];

		            					for(var i = 0; i < requiredArr.length; i++){
		            						var requiredKey = jqGridEnToCn[requiredArr[i]];
		            						if(requiredKey){
		            							messageMap.push(requiredKey);
		            						}else{
		            							messageMap.push(requiredArr[i]);
		            						}
		            					}
		            					//TODO
		            					for(var f=0;f<tableFieldsMap.length;f++){
		            						var param = {};
		            						param['fieldName']=tableFieldsMap[f].fieldName;
		            						param['comments']=tableFieldsMap[f].comments;
		            						selectParams.push(param);
		            					}
		            					
		            					for(var sheetName in sheetDataList){
		            						sheetNames.push(sheetName);//保存Excel表中每个sheet的名称
		            					}
		            					layer.close(index1);
		            					//执行第二步
		                                step_2();
		            				} else{
		            					AlertVoice.operateFailed(data.resultMsg);
		            				}
		            			}
		            		})
		                });
		            }
		        });
		    }
			
			//步骤2
		    function step_2() {
		        //步骤弹窗
		        var step2 = $("#step2").html();
		        //统一弹窗设置
		        //获取窗口高度
		        var index2 = layer.open({
		            type: 1,
		            title: '导入',
		            skin: "layer_upBox stepBoz2",
		            area: ['980px', '650px'],
		            resize: false,
		            shadeClose: true, //点击遮罩关闭
		            content: step2,
		            btnAlign: 'c',
		            zIndex: 100,
		            success: function () {
		                //由于插件在内容过多的情况下计算高度会有问题(这里做修复)
		                var upBox = $(".stepBoz2");
		                var height = Number(upBox.height()) - 42;
		                upBox.find(".layui-layer-content").css("height", height + "px");
		            	//动态添加导入文件名称栏
		                $(".numberselet").html();
				        for(var i = 0;i<sheetNames.length;i++){
				        	var name = sheetNames[i];
				        	if(i == 0){
				        		var radioView = "<li class='float-left margin-right4'><label class='v-raddioLabelBox' style='background-color: #e6e6e6; min-width: 48px'><input type='radio' name='snBit' value='"+name+"' checked><span>"+name+"</span></label></li>";	        		
				        	}else
				        		var radioView = "<li class='float-left margin-right4'><label class='v-raddioLabelBox' style='background-color: #e6e6e6; min-width: 48px'><input type='radio' name='snBit' value='"+name+"'><span>"+name+"</span></label></li>";
				        		$("#numberselet").append(radioView);
				        }
		                
		                //计算表格高度
		                var layerBox = $(".stepBoz2");
		                var tableHeight = layerBox.find(".centerBox").height() - (layerBox.find(".centerBox>.layer_info").height() + 20 + 42 + 52 + 16) - 1;

		                //初始化默认显示第一个sheet
		                if(sheetNames.length > 0){
		                	var sheetN = sheetNames[0];
		                    var firstF = $("input[name='show-border1']:checked").val();
		                    loadJqGrid(sheetN,firstF);
		                }
		                //返回上一步
						$("#returnStep_1").on("click",function(){
		                   layer.close(index2);
		                   step_1();
		                }); 
		                
		                //点击放弃
		                $("#closeindex2").on("click", function () {
		                    layer.close(index2)
		                });

		                //点击下一步
		                $("#toStep_3").on("click", function () {
		                	window.stuff_list4Table = $("#stuff_list4Table");
		                	var sname = $("input[name='snBit']:checked").val();
		                	var hasfield = $("input[name='show-border1']:checked").val();
		                    layer.close(index2);
		                    step_3(colName,colModel,sname,hasfield)
		                });
		            }
		        });
		    }
		    
		    //第一行包含列标题
		    $(document).on("change","[name='show-border1']",function(){
		    	var value = $(this).val();
		    	var sheetName = $("input[name='snBit']:checked").val();
		    	loadJqGrid(sheetName,value);
		    })
		 
		    //点击sheet名初始化列表
			$(document).on("change","[name='snBit']",function(){
		    	var value = $(this).val();
		    	var hasField = $("input[name='show-border1']:checked").val();
		    	loadJqGrid(value,hasField);
		    })
		   
		    //加载弹框列表方法，columnName是jqGrid列表的表头，columnModel是jqGrid列表的model，sheetName是选中的sheet的名称(ID)，sheetData是
		    function loadJqGrid(sheetName,hasField){
		    	var sheet = [];
		    	sheet = sheetDataList[sheetName];
		    	sheetData = [];//保存jqGrid特定的数据格式的所有数据
				var fieldnum = 0;//获取excel表字段个数
				colName = [];
				colModel = [];
				//获取Excel表中字段值最多的一行的个数
				for(var num=0;num<sheet.length;num++){
					if(fieldnum<sheet[num].length){
						fieldnum=sheet[num].length;
					}
				}
				if(hasField == "Y"){
					if(fieldnum<=sheet[0].length){
						/*for(var j=0;j<sheet[0].length;j++){
							colName.push(sheet[0][j]);
						}*/
						/** 2020.03.11-优化 */
						colName = sheet[0];
					}else{
						var firstnum=sheet[0].length;
						for(var j=0;j<fieldnum;j++){
							if(j<firstnum){
								/*if(sheet[0][j] != ""){
									colName.push(sheet[0][j]);
								}else{
									colName.push("Field_"+(j+1));
								}*/
								/** 2020.03.11-优化 */
								colName.push( sheet[0][j]!=""? sheet[0][j]:("Field_"+(j+1)) );
							}else{
								colName.push("Field_"+(j+1));
							}
						}
					}
					for(var k=0;k<colName.length;k++){
						colModel.push({name:colName[k],index:'amount',align:'left'});
					}
					//构造表格字段属性
					var stlength = sheet.length>10?10:sheet.length;
					for(var a=1;a<stlength;a++){
						var row = {};
						for(var b=0;b<sheet[a].length;b++){
							row[colName[b]] = sheet[a][b];
						}
						sheetData.push(row);
					}
				}else{
					//构造Excel无表头时的表头字段
					for(var j=1;j<=fieldnum;j++){
						colName.push("Field_"+j);
					}
					for(var k=0;k<colName.length;k++){
						colModel.push({name:colName[k],index:'amount',align:'left'});
					}
					//构造表格字段属性
					for(var a=0;a<(sheet.length>10?10:sheet.length);a++){
						var row = {};
						for(var b=0;b<sheet[a].length;b++){
							row["Field_"+(b+1)] = sheet[a][b];
						}
						sheetData.push(row);
					}
				}
				//由于插件在内容过多的情况下计算高度会有问题(这里做修复)
		        var upBox = $(".stepBoz2");
		        var height = Number(upBox.height()) - 42;
		        upBox.find(".layui-layer-content").css("height",height+"px");

		        //计算表格高度
		        var layerBox = $(".stepBoz2");
		        var tableHeight = layerBox.find(".centerBox").height() - (layerBox.find(".centerBox>.layer_info").height()+20+42+52+16) -1;
		        
		        //弹窗内部表格
		        selfTabel("#stuff_list4",{
		        	datatype: "json",//请求数据返回的类型。可选json,xml,txt
		            colNames: colName,//jqGrid的列显示名字,默认左对齐,如果要居中,则用p元素包裹
		            colModel: colModel,
		            multiselect: false,
		            multiselectWidth: 30,
		            rowNum: 10,
		            height: tableHeight,
		            card: {
		                menu: [{
		                    icon: "icon iconfont icon-fuzhi",
		                    text: "编辑",
		                    name: "delet"
		                }, {
		                    icon: "icon iconfont icon-fuzhi",
		                    text: "编辑",
		                    name: "retrun"
		                }, {
		                    icon: "icon iconfont icon-xiugai",
		                    text: "修改",
		                    name: "alter"
		                }, {
		                	icon: "icon iconfont icon-xiugai", 
		                	text: "修改", 
		                	name: "alter"
		                }],//弹出选择操作
		            },
		            loadComplete: function (data) {
		            	
		            }
		        });
		        setTimeout(function(){
		        	$("#stuff_list4Table").jqGrid('clearGridData');
		        	$("#stuff_list4Table").jqGrid('addRowData',1,sheetData);
		        },150)
		    }
		    
		    //步骤3
		    function step_3(colN,colM,sname,hfield) {
		        //步骤弹窗
		        var step3 = $("#step3").html();
		        //统一弹窗设置
		        //获取窗口高度
		        var index3 = layer.open({
		        	type: 1,
		            title: '导入',
		            skin: "layer_upBox stepBoz3",
		            area: ['980px', '650px'],
		            resize: false,
		            shadeClose: true, //点击遮罩关闭
		            content: step3,
		            btnAlign: 'c',
		            zIndex: 100,
		            success: function () {
		                //由于插件在内容过多的情况下计算高度会有问题(这里做修复)
		                var upBox = $(".stepBoz3");
		                var height = Number(upBox.height()) - 42;
		                upBox.find(".layui-layer-content").css("height", height + "px");
		                
		                for(var f = 0; f < messageMap.length; f++){
		                	var message = messageMap[f];
		                	var selectView = "<li><div class='active' data-id='"+f+"'>"+message+"</div></li>"
		                	$("#selectparam").append(selectView);
		                }
		                //计算表格高度
		                var layerBox = $(".stepBoz3");
		                var tableHeight = layerBox.find(".centerBox").height() - (layerBox.find(".centerBox>.clearfix").height() + 40 + 20 + 42 + 52 + 16) - 1;
		                //返回上一步
		                $("#returnStep_2").on("click", function () {
		                    layer.close(index3);
		                    step_2();
		                });
		                //下一步
		                $("#toStep_4").on("click", function () {
		                    //判断必填字段是否都存在
		                	var head = getToBoj();
		                	var fields = [];
		                	for(var k in head){
		                		if(head[k].text == ""){
		                			fields.push(k);
		                		}else{
		                			fields.push(head[k].text)
		                		}
		                	}
		                	for(var m = 0; m < messageMap.length; m++){
		                		if(fields.indexOf(messageMap[m])==-1){
		                			AlertVoice.operateFailed(messageMap[m]+"是必填字段");
		                			return ;
		                		}
		                	}
		                	layer.close(index3);
		                    step_4(judgeType,colN,colM,sname,hfield);
		                });
		                //关闭
		                $("#closeindex3").on("click", function () {
		                    layer.close(index3);
		                });
		                var step3ColName = [];
		                for(var s=0;s<colN.length;s++){
		                	var s3Field = "<div>"+colN[s]+"<div class='moveSeletList'>TO</div></div>";
		                	step3ColName.push(s3Field);
		                }
		                //弹窗内部表格
		                selfTabel("#stuff_list5", {
		                	datatype: "json",//请求数据返回的类型。可选json,xml,txt
		                    colNames: step3ColName,//jqGrid的列显示名字,默认左对齐,如果要居中,则用p元素包裹
		                    colModel: colM,
		                    multiselect: false,
		                    multiselectWidth: 30,
		                    rowNum: 10,
		                    height: tableHeight,
		                    card: {
		                        menu: [{
		                            icon: "icon iconfont icon-fuzhi",
		                            text: "编辑",
		                            name: "delet"
		                        }, {
		                            icon: "icon iconfont icon-fuzhi",
		                            text: "编辑",
		                            name: "retrun"
		                        }, {
		                            icon: "icon iconfont icon-xiugai",
		                            text: "修改",
		                            name: "alter"
		                        }, {
		                        	icon: "icon iconfont icon-xiugai", 
		                        	text: "修改", 
		                        	name: "alter"
		                        }],//弹出选择操作
		                    },
		                    loadComplete: function (data) {
		                    	
		                    }
		                });
		                //可以移动事件
		                var move = false;
		                var moveEl;
		                var moveStart = {};
		                var moveToEl;
		                $(".moveListBox li>div").on("mousedown", function (e) {
		                    if ($(this).hasClass("active")) {
		                        moveEl = $(this);
		                        move = true;
		                        moveStart.y = e.pageY;
		                        moveStart.x = e.pageX;
		                        moveEl.css('z-index', 10000);
		                    }
		                });
		                $("body").on("mouseup", function (e) {
		                    if (move) {
		                        moveEl.css({'top': '0px', 'left': '0px'});
		                        moveToEl = document.elementFromPoint(e.pageX, e.pageY);
		                        if (moveToEl.parentNode.parentNode.parentNode.nodeName === 'TH') moveToEl = moveToEl.parentNode.parentNode.parentNode;
		                        if (moveToEl.parentNode.parentNode.nodeName === 'TH') moveToEl = moveToEl.parentNode.parentNode;
		                        if (moveToEl.parentNode.nodeName === 'TH') moveToEl = moveToEl.parentNode;
		                        if (moveToEl.nodeName === 'TH') {
		                            var cBox = $(moveToEl).find(".moveSeletList").find("p");
		                            if (!cBox.length) {
		                                $(moveEl).removeClass("active");
		                                $(moveToEl).find(".moveSeletList").append("<p data-id='" + $(moveEl).attr('data-id') + "'>" + $(moveEl).html() + "<span></span></p>");
		                            }
		                            $(moveToEl).removeClass("moveElHover");
		                        }
		                    }
		                    moveEl.css('z-index', 1);
		                    move = false;
		                })
		                $("body").on("mousemove", function (e) {
		                    if (moveToEl) $(moveToEl).removeClass("moveElHover");
		                    if (move) {
		                        var x = e.pageX - moveStart.x;
		                        var y = e.pageY - moveStart.y;
		                        moveEl.css({'top': y + 'px', 'left': x + 'px'});
		                        moveEl.hide();
		                        moveToEl = document.elementFromPoint(e.pageX, e.pageY);
		                        if (moveToEl.parentNode.parentNode.parentNode.nodeName === 'TH') moveToEl = moveToEl.parentNode.parentNode.parentNode;
		                        if (moveToEl.parentNode.parentNode.nodeName === 'TH') moveToEl = moveToEl.parentNode.parentNode;
		                        if (moveToEl.parentNode.nodeName === 'TH') moveToEl = moveToEl.parentNode;
		                        if (moveToEl.nodeName === 'TH') {
		                            $(moveToEl).addClass("moveElHover");
		                        }
		                        moveEl.show();
		                    }
		                })
		                $(".moveSeletList").on("click", "span", function (e) {
		                    var id = $(this.parentNode).attr("data-id");
		                    $(this.parentNode).remove();
		                    $(".moveListBox div[data-id='" + id + "']").addClass("active");
		                })
		            }
		        });
		        //构造数据
		        var sheet = sheetDataList[sname];
		        var sheetD = [];
		        colName = [];
		        if(hfield == "Y"){
		        	for(var j=0;j<sheet[0].length;j++){
		            	colName.push(sheet[0][j]);
		            }
		            for(var a=1;a<sheet.length;a++){
		            	var row = {};
		            	for(var b=0;b<sheet[a].length;b++){
		            		row[colName[b]] = sheet[a][b];
		            	}
		            	sheetD.push(row);
		            }
		        }else{
		        	for(var j=0;j<colN.length;j++){
		            	colName.push(colN[j]);
		            }
		            for(var a=0;a<sheet.length;a++){
		            	var row = {};
		            	for(var b=0;b<sheet[a].length;b++){
		            		row[colName[b]] = sheet[a][b];
		            	}
		            	sheetD.push(row);
		            }
		        }
		        setTimeout(function(){
		        	$("#stuff_list5Table").jqGrid('addRowData',1,sheetD);;
		        },150)
		    }

		    //步骤4
		    function step_4(judgeType,colN,colM,sname,hfield) {
		    	var sheetTable = $('#stuff_list5Table').jqGrid("getRowData");//获取Table数据，键值对
		    	var sheetData = [];//保存转义后的键值对数据
		    	var sheetDataArray = [];//保存键值对对象的数组
		    	var headCode = [];
		    	//获取更改后的表头结构
		    	var head = getToBoj();
		    	var headRow = new Array();//保存新表头的字段名称
			    var replaceHead = {};//保存被替换的字段键值对，键是替换前，值是替换后
		    	var row = new Array();
		    	
		    	/**
		    	 * 2020.02.17新增
		    	 */
		    	//获取所有替换的必填值
		    	for(var i in head){
		    		if(head[i].text != ""){
		    			replaceHead[i] = head[i].text;
		    		}
		    	}
		    	
		    	/**
		    	 * 2020.02.17新增
		    	 */
		    	for(var j = 0; j < sheetTable.length; j++){
		    		var oneRow = sheetTable[j];
		    		var Row = {};
		    		for(var m in oneRow){
		    			var repCell = replaceHead[m];
		    			var boxKeyToVal = {}; //保存字段转义
		    			//判断该字段是否被替换
		    			if(repCell){
		    				boxKeyToVal = nameMapValue[repCell];
		    				if(boxKeyToVal){
		    					Row[repCell] = boxKeyToVal[oneRow[m]];
		    				}else{
		    					Row[repCell] = oneRow[m];
		    				}
		    			}else{
		    				boxKeyToVal = nameMapValue[m];
		    				if(boxKeyToVal){
		    					Row[m] = boxKeyToVal[oneRow[m]];
		    				}else{
		    					Row[m] = oneRow[m];
		    				}
		    			}
		    		}
		    		sheetDataArray.push(Row);
		    	}
		    	
		    	/**
		    	 * 2020.02.17新增   jqGridHeader
		    	 */
		    	var newHeadKeyToValue = {};//保存新的表头
		    	for(var i = 0; i < sheetDataArray.length; i++){
		    		var R = sheetDataArray[i];
		    		var L = {};
		    		for(var r in R){
		    			for(var j in jqGridHeader){
		    				if(j == r){
		    					//存在不可填字段直接忽略
		    					if(unrequired.indexOf(jqGridHeader[j])!= -1){
		    						break;
		    					}else{
			    					L[jqGridHeader[j]] = R[r];
			    					newHeadKeyToValue[jqGridHeader[j]] = r;
			    					break;
		    					}
		    				}
		    			}
		    		}
		    		sheetData.push(L);
		    	}
		    	
		    	//校验
		    	var excelHead = [];
		    	var legalDatas = {};
		    	var errMsgs = {};
		    	if(extend1){
		    		extend1.extend["sheetData"] = JSON.stringify(sheetData);
			    	extend1.extend["requiredArr"] = JSON.stringify(required);
			    	extend1.extend["unrequiredArr"] = JSON.stringify(unrequired);
			    	extend1.extend["isBom"] = JSON.stringify(isBom);
		    	}else{
		    		var e1 = {};
		    		var extend = {};
		    		extend["sheetData"] = JSON.stringify(sheetData);
		    		extend["requiredArr"] = JSON.stringify(required);
		    		extend["unrequiredArr"] = JSON.stringify(unrequired);
		    		extend["isBom"] = JSON.stringify(isBom);
		    		e1["extend"] = extend;
		    		extend1 = e1;
		    	}
		    	RestfulClient.post(verifyExcelUrl,extend1/*{
		    		"extend":{
		    			"sheetData":JSON.stringify(sheetData),
		    			"requiredArr":JSON.stringify(required),
		    			"unrequiredArr":JSON.stringify(unrequired),
		    			"extend" : JSON.stringify(extend)
		    		}
		    	}*/,function(rdata){
		    			legalDatas = rdata.extend.legalDatas;//合法数据
		    			errMsgs = rdata.extend.errMsgs;//错误信息
		    			var excelForm = [];//弹框的jqGrid
		    			
	    			//一般导入对整体数据的合法性进行校验
		    		if(beforeFunc){
						beforeFunc(legalDatas,errMsgs,beforeParam);
					}
		    			
		    		for(var k in legalDatas){
	    				var legalData = legalDatas[k];
	    				var row = {};
	    				for(var l in newHeadKeyToValue){
	    					var lv = legalData[l];
	    					var cn = newHeadKeyToValue[l];//字段中文名
	    					if(lv){
	    						var boxMapToVal = {};
	    						boxMapToVal = nameMapValue[cn];
	    						if(boxMapToVal){
	    							for(var i in boxMapToVal){
	    								if(lv == boxMapToVal[i]){
	    									row[cn] = i;
	    								}
	    							}
	    						}else{
	    							row[cn] = lv;
	    						}
	    					}
	    				}
	    				excelForm.push(row);
		    		}
		    		
			        //步骤4弹窗
			        var step4 = $("#step4").html();
			        var index4 = layer.open({
			            type: 1,
			            title: '导入',
			            skin: "layer_upBox stepBoz4",
			            area: ['980px', '650px'],
			            resize: false,
			            shadeClose: true, //点击遮罩关闭
			            content: step4,
			            btnAlign: 'c',
			            zIndex: 100,
			            viewrecords: true,
			            success: function () {
			                //由于插件在内容过多的情况下计算高度会有问题(这里做修复)
			                var upBox = $(".stepBoz4");
			                var height = Number(upBox.height()) - 42;
			                upBox.find(".layui-layer-content").css("height", height + "px");
			                
			                //插入错误信息
			                for(var e in errMsgs){
			                	var eMsg = errMsgs[e];
			                	for(var m=0;m<eMsg.length;m++){
			                		var errM = "<li>"+eMsg[m]+"</li>";
			                		$("#errormsg").append(errM);
			                	}
			                }
			                var excelHead = [];
			                var form = excelForm[0];
			                if(form){
			                	for(var names in form){
			                		excelHead.push(names);
			                	}
			                }
			                var excelModel = [];
			                for(var k=0;k<excelHead.length;k++){
			                	excelModel.push({name:excelHead[k],index:'amount',align:'left'});
			        		}
			                //弹窗内部表格
			                selfTabel("#stuff_list6", {
			                    datatype: "json",//请求数据返回的类型。可选json,xml,txt
			                    colNames: excelHead,
			                    colModel: excelModel,
			                    multiselect: false,
			                    multiselectWidth: 30,
			                    rowNum: 10,
			                    height: 210,
			                    card: {
			                        menu: [{
			                            icon: "icon iconfont icon-fuzhi",
			                            text: "编辑",
			                            name: "delet"
			                        }, {
			                            icon: "icon iconfont icon-fuzhi",
			                            text: "编辑",
			                            name: "retrun"
			                        }, {
			                            icon: "icon iconfont icon-xiugai",
			                            text: "修改",
			                            name: "alter"
			                        }, {icon: "icon iconfont icon-xiugai", text: "修改", name: "alter"}],//弹出选择操作
			                    },
			                    loadComplete: function (data) {
			                        
			                    }
			                });
			
			                //返回上一步
							$("#returnStep_3").on("click",function(){
			                   layer.close(index4);
			                   step_3(colN,colM,sname,hfield);
			                }); 
							//点击重置按钮
						    $("#reset").on("click",function(){
						    	resetExcel();
						    });
			                //继续
			                $("#closeindex4").on("click", function () {
			                	if(afterFunc){
			                    	afterFunc(rdata,afterParam,fileFormData);
			                    }
			                	intoGrid(judgeType,legalDatas,excelHead,newHeadKeyToValue,$tableName);
			                    layer.close(index4);
			                });
			                //取消
			                $("#closeindex5").on("click", function () {
			                    layer.close(index4);
			                });
			            }
			        });
			        if($.isEmptyObject(errMsgs)){
			        	if(afterFunc){
	                    	afterFunc(rdata,afterParam,fileFormData);
	                    }
			        	intoGrid(judgeType,legalDatas,excelHead,newHeadKeyToValue,$tableName);
			        	layer.close(index4);
			        }else{
			        	setTimeout(function(){
		                	 $("#stuff_list6Table").jqGrid('addRowData',1,excelForm);
				        },150)
			        }
		    	})
		    }
		    
		    //获取更改后的表头结构
		    function getToBoj(){
		        var box = $("#stuff_list5 thead th .ui-jqgrid-sortable>div");
		        var data = {};
		        for(var i=0;i<box.length;i++){
		            var d = $(box[i]);
		            var key = d.text().split('TO')[0].trim();
		            var vule = {
		                id:null,
		                text:""
		            };
		            if(d.find("p[data-id]")){
		                vule.id = d.find("p[data-id]").attr('data-id');
		                vule.text = d.find("p[data-id]").text();
		            }
		            data[key] = vule;
		        }
		        return data;
		    }
		    /**
		     * 单表传输数据到后台新增，多表将数据导入jqGrid表格
		     * @param judgeType 0为单表，1为多表
		     * @param legalDataas 合法数据
		     * @param excelHead 弹框的jqGrid表头
		     * @param $tableName 子表jqGrid的table
		     */
		    function intoGrid(judgeType,legalDatas,excelHead,newHeadKeyToValue,$tableName){
		    	if(judgeType == "1"){
			    	var excelHeadCode = [];//保存表头结构的Code
			    	var data = {};
			    	window.clearMtrlList = [];//删除行
			    	var ids = $tableName.jqGrid('getDataIDs');
			    	
			    	/*删除table中使用弹框新增的记录*/
			    	for(var i=0; i<ids.length; i++){
			    		var row = $tableName.jqGrid("getRowData",ids[i]);
			    		if(!row.updatedDate){
			    			appUtils.delCard(ids[i], $tableName);
			    		}
			    	}
			    	
					for(var e=0;e<excelHead.length;e++){
						for(var t in selectParams){
							if(excelHead[e] == selectParams[t].comments){
								excelHeadCode.push(selectParams[t].fieldName);
								break;
							}
						}
					}
					for(var z in legalDatas){
						var legalData = legalDatas[z];
						var d = {};
						for(var x=0;x<excelHeadCode.length;x++){
							d[excelHeadCode[x]]="";
						}
						var c = 0;
						for(var b in legalData){
							d[b] = legalData[b];
						}
						var options = {
							data : d,
							table : $tableName//Table
						};
						appUtils.addCard(options);//添加到表中
					}
			    }else{
			    	if(legalDatas){
				    	var exHead = [];
				    	var form = [];
				    	
				    	/**
				    	 * 2020.03.13 修改
				    	 */
				    	var obj = legalDatas[0];
				    	for(var j in obj){
				    		exHead.push(newHeadKeyToValue[j]);
				    	}
				    	
				    	form.push(exHead);
				    	for(var k in legalDatas){
				    		var dto = legalDatas[k];
				    		var arr = [];
				    		for(var v in dto){
				    			arr.push(dto[v]);
				    		}
				    		form.push(arr);
				    	}
				    	if(extend2){
				    		extend2.extend["list"] = JSON.stringify(form);
				    		extend2.extend["requiredArr"] = JSON.stringify(required);
				    		extend2.extend["unrequiredArr"] = JSON.stringify(unrequired);
				    	}else{
				    		var e2 = {};
				    		var extend = {};
				    		extend["list"] = JSON.stringify(form);
				    		extend["requiredArr"] = JSON.stringify(required);
				    		extend["unrequiredArr"] = JSON.stringify(unrequired);
				    		e2["extend"] = extend;
				    		extend2 = e2;
				    	}
				    	/*var data = {
				    		extend : {
				    			//需要保存的数据
				    			list : JSON.stringify(form),
				    			requiredArr:JSON.stringify(required),
				    			unrequiredArr:JSON.stringify(unrequired),
				    			extend : JSON.stringify(extend)
				    		}
				    	}*/
				    	//单表类型的导入，发送请求到后端将数据插入数据库
				    	RestfulClient.post(insertExcelUrl,/*data*/extend2,function(data){
				    		if(data.resultCode == "0000"){
				    			AlertVoice.saveSuccess("");
				    			window.location.reload();
				    		}else{
				    			layer.close(index4);
				    		}
				    	})
			    	}else{
			    		layer.close(index4);
			    	}
			    }
		    }
		    //重置方法
		    function resetExcel(){
		    	//加载文件
                publicUtils.loadFileinput("#input-iconic1",{preferIconicPreview:false,showPreview:false});
                //$('#input-iconic1').on('fileselect', function(event, numFiles, label) {
            		var formData = new FormData();
            		formData.append('file',$('#input-iconic1')[0].files[0]);
            		formData.append('reParam',requiredArr);
            		$.ajax({url : parseExcelUrl,type : "POST",cache : false,
            			data : formData,
            			traditional : true,//设置为true,否则后台接收的参数会带上[]，无法正常接收
            			processData : false,
            			contentType : false,
            			dataType : "json",
            			success : function(data) {
            				if (data.resultCode == '0000') {
            					sheetDataList = [];
            					tableFieldsMap = [];
            					messageMap = [];
            					sheetDataList = data.extend.sheetListMap;//Excel表数据（每个sheet对应一个数据数组）
            					tableFieldsMap = data.extend.tableFieldsMap;//保存了整个表的字段名
            					messageMap = data.extend.messageMap;//保存必填字段的国际化键值对
            					sheetNames=[];
            					selectParams=[];
            					for(var f=0;f<tableFieldsMap.length;f++){
            						var param = {};
            						param['fieldName']=tableFieldsMap[f].fieldName;
            						param['comments']=tableFieldsMap[f].comments;
            						selectParams.push(param);
            					}
            					for(var sheetName in sheetDataList){
            						sheetNames.push(sheetName);//保存Excel表中每个sheet的名称
            					}
            					layer.close(index1);
            					//执行第二步
                                step_2();
            				} else{
            					AlertVoice.operateFailed(data.resultMsg);
            				}
            			}
            		})
                //});
		    }
		}
	}
})(jQuery);